package com.atguigu.springsecuritydemo.service;

import com.atguigu.springsecuritydemo.entity.User;
//import com.atguigu.springsecuritydemo.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: robert.song
 * @Date: Created in 2022/3/20
 */
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

//    @Autowired
//    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        User user = userMapper.selectOne(wrapper);
//        此处模拟一个sql返回的user，简单省事
        User user = new User(1, "user", "123");
        if (user.getUsername() != username) {
            throw new UsernameNotFoundException("账号无法匹配");
        }
//        模拟账号的权限，权限不可为null
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");

        return new org.springframework.security.core.userdetails.User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), auths);

    }
}
